<?php

namespace app\services\analysis;

use app\dao\user\UserDao;
use app\services\BaseServices;
use app\model\user\User;
use app\model\product\product\StoreProductRelation;
use app\model\order\StoreOrder;
use app\model\order\StoreOrderCartInfo;

class UserServices extends BaseServices
{
    public function __construct(UserDao $dao)
    {
        $this->dao = $dao;
    }

    /**
     * @return int[]
     */
    public function overview(){
        $data = [
            'today' => 0,
            'today_proportion' => 100.00,
            'yesterday' => 0,
            'week' => 0,
            'month' => 0,
        ];
        $today_dateline = strtotime(date('Y-m-d'));
        $today = User::field('count(*) number')->where('status',1)->where('is_del',0)->where('add_time','>=',$today_dateline)->find()->toArray();
        $data['today'] = $today['number'] ? (int)$today['number'] : 0;

        $yesterday_dateline = $today_dateline - 86400;
        $yesterday = User::field('count(*) number')->where('status',1)->where('is_del',0)->where('add_time','>=',$yesterday_dateline)->where('add_time','<', $today_dateline)->find()->toArray();
        $data['yesterday'] = $yesterday['number'] ? (int)$yesterday['number'] : 0;

        $week_dateline = $today_dateline - (86400 * 6);
        $week = User::field('count(*) number')->where('status',1)->where('is_del',0)->where('add_time','>=', $week_dateline)->find()->toArray();
        $data['week'] = $week['number'] ? (int)$week['number'] : 0;

        $month_dateline = strtotime(date('Y-m-01'));
        $month = User::field('count(*) number')->where('status',1)->where('is_del',0)->where('add_time','>=', $month_dateline)->find()->toArray();
        $data['month'] = $month['number'] ? (int)$month['number'] : 0;

        if($data['yesterday'] > 0){
            $data['today_proportion'] = $this->truncateDecimal(abs(($data['today'] - $data['yesterday']))/$data['today'] * 100);
        }
        return $data;
    }

    /**
     * @return array
     */
    public function add_detail($param){
        $data = [
            'number' => [],
            'target' => [],
        ];
        $p = $this->check_param($param);
        $target = $this->get_date($p);

        $data['target'] = $target;
        $adds = User::field("DATE_FORMAT(FROM_UNIXTIME(add_time), '%Y-%m-%d') date_time,count(*) number")
            ->where('add_time','>=',$p['start_time'])->where('add_time','<',$p['end_time'])
            ->group("DATE_FORMAT(FROM_UNIXTIME(add_time), '%Y-%m-%d')")->select()->toArray();
        if($adds){
            foreach ($target as $date){
                $tem = 0;
                foreach ($adds as $num){
                    if($date == $num['date_time']){
                        $tem = $num['number'];
                    }
                }
                $data['number'][] = $tem;
            }
        }
        return $data;
    }

    /**
     * @return array|array[]
     */
    public function active_date_detail($param){
        $data = [];
        $data['number'] = [10,20,30,40];
        $data['target'] = ['11-01','11-02','11-03','11-04'];
        return $data;
    }

    /**
     * @return array|array[]
     */
    public function active_time_detail($param){
        $data = [];
        $data['number'] = [10,20,30,40,10,20,30,40,10,20,30,40,10,20,30,40,10,20,30,40,10,20,30,40,];
        $data['target'] = ['01','02','03','04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24'];
        return $data;
    }

    /**
     * @return array|array[]
     */
    public function read_detail($param){
        $data = [];
        $data['number'] = [10,20,30,40,10,20,30,40,10,20,];
        $data['target'] = ['商品1','商品2','商品3','商品4','商品5','商品6','商品7','商品8','商品9','商品10'];
        return $data;
    }

    /**
     * @return array
     */
    public function collect_detail($param){
        $data = [
            'number' => [],
            'target' => [],
        ];
        $p = $this->check_param($param);
        $products = StoreProductRelation::alias('c')->field('count(*) number, c.product_id, p.store_name')
            ->where('c.add_time','>=',$p['start_time'])->where('c.add_time','<',$p['end_time'])
            ->where('c.type','collect')->where('c.category','product')->group('c.product_id')
            ->join('store_product p', 'p.id = c.product_id')
            ->select()->toArray();

        if($products){
            $numbers = array_column($products,'number');
            array_multisort($numbers,SORT_DESC,$products);
            $products = array_slice($products,0,10);

            $data['number'] = array_column($products,'number');
            $data['target'] = array_column($products,'store_name');
        }
        return $data;
    }

    /**
     * @return array
     */
    public function buy_detail($param){
        $data = [
            'number' => [],
            'target' => [],
        ];
        $p = $this->check_param($param);
        $products = StoreOrderCartInfo::alias('c')->field('sum(c.surplus_num) number, c.product_id, p.store_name')
            ->where('o.add_time','>=',$p['start_time'])->where('o.add_time','<',$p['end_time'])
            ->where('o.status','in',[1,2,3])->group('c.product_id')
            ->join('store_order o', 'o.id = c.oid')
            ->join('store_product p', 'p.id = c.product_id')
            ->select()->toArray();

        if($products){
            $numbers = array_column($products,'number');
            array_multisort($numbers,SORT_DESC,$products);
            $products = array_slice($products,0,10);

            $data['number'] = array_column($products,'number');
            $data['target'] = array_column($products,'store_name');
        }
        return $data;
    }

    /**
     * @param $param
     * @return mixed
     */
    public function check_param($param){
        if(!isset($param['start_time']) || $param['start_time'] == ''){
            $param['start_time'] = strtotime(date('Y-m-01'));
        }
        if(!isset($param['end_time']) || $param['end_time'] == ''){
            $param['end_time'] = strtotime(date('Y-m-d')) + 86400;
        }
        return $param;
    }

    /**
     * @param $param
     * @return array
     */
    public function get_date($param){
        $dates = [];
        $no = ($param['end_time'] - $param['start_time']) / 86400;
        for ($i = 0; $i < $no; $i++){
            $dates[] = date('Y-m-d',$param['start_time'] + $i * 86400);
        }
        return $dates;
    }

    /**
     * @param $numberString
     * @param int $precision
     * @return string
     */
    public function truncateDecimal($numberString, $precision = 2) {
        // 查找小数点的位置
        $pos = strpos($numberString, '.');
        if ($pos === false) {
            // 如果没有小数点，则直接返回字符串（或添加小数点并填充零）
            return $numberString . '.' . str_repeat('0', $precision);
        }
        // 截取小数点后的部分
        $decimalPart = substr($numberString, $pos + 1);
        // 保留指定的小数位数
        $truncatedDecimalPart = substr($decimalPart, 0, $precision);
        // 拼接整数部分和截取后的小数部分
        return substr($numberString, 0, $pos + 1) . $truncatedDecimalPart;
    }

    /**
     * @param $year
     * @return array
     */
    public function getAllMonthsOfYear($year) {
        $months = array();
        for ($i = 1; $i <= 12; $i++) {
            $months[] = date('Y-m', strtotime("$year-$i-01")); // 使用date和strtotime函数获取月份的全名
        }
        return $months;
    }
}